package com.lxq.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.lxq.entity.User;

/**
 * Servlet Filter implementation class SecurityFilter
 */
@WebFilter("/app/mng/*")
public class SecurityFilter implements Filter {

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		
		User user = (User)req.getSession().getAttribute("curr_user");
		if(user != null){
			chain.doFilter(req, res);
		}else{
			response.setContentType("application/json;charset=UTF-8");
			
			JSONObject json = new JSONObject();
			try {
				json.put("state", "fail");
				json.put("msg", "后台操作请先登录");
				
				response.getWriter().print(json);
				response.getWriter().flush();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
